class Solution {
public:
    int trap(vector<int>& height) {
        int water = 0;
        deque<int> tell;
        for(int i=0;i<height.size();i++)
        {
            int h = height[i];
            if(h>0)
            {
                int f = 0;
                int d = 0;
                while(!tell.empty())
                {
                    int i1 = tell.back(),h1 = height[i1];
                    f+=(min(h,h1) - d)*(i-i1-1);
                    d=h1;
                    if(h1>h)
                    {
                        break;
                    }
                    else
                        tell.pop_back();
                }
                tell.push_back(i);
                water+= f;
            }
        }
        return water;
    }
};
